package longrise.phone.com.bjjt_henan;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.baidu.mobstat.StatService;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.LEAP.Base.Objects.UserInfo;
import com.longrise.android.FrameworkManager;
import com.longrise.android.Global;
import com.longrise.android.ILSMsgListener;
import com.longrise.android.ILSTaskListener;
import com.longrise.android.LFActivity;
import com.longrise.android.errorlog.UncaughtException;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.updata.UpdataAPK;
import com.longrise.bjjt.util.PrefUtils;
import com.longrise.bjjt.util.UiUtil;
import com.umeng.socialize.UMShareAPI;

import longrise.phone.com.bjjt_henan.Constant.URLConstant;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.Utils.DialogUtils;
import longrise.phone.com.bjjt_henan.font.FontStyle;
import longrise.phone.com.bjjt_henan.lunchandlogin.HeNanLoginView;
import longrise.phone.com.bjjt_henan.widget.PromptDialog;

public class MainActivity extends LFActivity implements ILSTaskListener, ILSMsgListener, Callback, UncaughtException.OnExceptionEvent {
    private boolean isRestart = false;
    private LinearLayout _bodyView = null;
    private HeNanLoginView _portMenu = null;
    private SharedPreferences sharedPreferences;
    private OnActivityReturnBitmap activityReturnBitmap;
    private PromptDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            this.isExit = false;
            // Activity 级定时任务 (super.onCreate之前)
            // this.setILSTaskListener(this, 1000 * 60 * 10);
            super.onCreate(savedInstanceState);

            //程序崩溃信息记录，在/baoa_error/log/目录下
            UncaughtException mUncaughtException = UncaughtException.getInstance();
            mUncaughtException.init(this, this.getString(R.string.appRootDir), this);

            // 全局Form窗口设置
            // 此注释请勿删除 lilw
            this.setFormTitleTextColor(Color.parseColor("#eb7e00")); // 窗口标题内容颜色
            this.setFormTitleTextTypeface(new FontStyle(this).getTypeface());// 窗口标题内容字体
            this.setFormTitleTextFontSize(23f); // 窗口标题内容字体大小
            this.setFormSwitchbuttontextColor(Color.parseColor("#666666")); // 窗口切换框未选中切换按钮的字体颜色
            this.setFormSwitchbuttontextSelectedColor(Color.parseColor("#1752a4"));// 窗口切换框选中切换按钮的字体颜色
            this.setFormSwitchButtonTextFontSize(21f); // 窗口切换框切换按钮的字体大小
            this.setFormSwitchButtonTextTypeface(new FontStyle(this).getTypeface());// 窗口切换框切换按钮的字体类型
            this.setFormSwitchButtonSize(185, 70, 70, 185); // 窗口切换按钮的尺寸（横向切换按钮的宽,横向切换按钮的高,纵向切换按钮的宽,纵向切换按钮的高)
            this.setFormTitleHeight(-1); // 设置窗口标题高度，<=0为自适应 默认0
            this.setFormTitleMinHeight(75); // 设置窗口标题栏最小高度，默认60
            this.setFormTitleTagSize(5, 30); // 设置窗口标题标签尺寸，默认 (5,30)
            this.setFormTitleCloseButtonSize(-1, 60); // 设置窗口关闭按钮尺寸，默认 (60,50)
            // <=0为自适应
            this.setFormTitleCloseButtonTextFontSize(14f); // 设置窗口关闭按钮字体大小 默认
            // 22f
            this.setFormTitleCloseButtonTextTypeface(new FontStyle(this).getTypeface());
            this.setAppRootDir(this.getString(R.string.appRootDir));

            // =======================================添加菜单界面==================================
            this.addILSMsgListener(this); // 加入系统级事件监听
            this._bodyView = this.getBodyView();// 当前框架view
            if (null == this._bodyView)
                return;
            this._bodyView.removeAllViewsInLayout();

            this.setFormMargin(0, 0, 0, 0);// 设置Form的外边距
            if (null == this._portMenu) {
                this._portMenu = new HeNanLoginView(this);
                this._portMenu.init();
            }
            this._portMenu.refresh();
            this._bodyView.addView(this._portMenu.getView(),
                    new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

            PackageManager pm = this.getPackageManager();
            if (null != pm) {
                PackageInfo packageInfo = pm.getPackageInfo(this.getPackageName(), 0);
                if (null != packageInfo) {
                    Global.getInstance().setVersionCode(packageInfo.versionCode);
                    Global.getInstance().setVersionName(packageInfo.versionName);
                }
                packageInfo = null;
            }
            // add by luoyi ================全局参数初始化====================
            ((BaseApplication) this.getApplicationContext()).setBaseServerUrl
                    (getResources().getString(R.string.kckpServerUrl));// 周市委基础登录地址外网

            ((BaseApplication) this.getApplicationContext()).setServerUrl
                    (getResources().getString(R.string.kckpServerUrl));//快处快赔业务外网地址

            ((BaseApplication) this.getApplicationContext()).setUpdateUrl(getResources
                    ().getString(R.string.kckpupdateUrl));// apk升级地址

            //默认地址
            ((BaseApplication) this.getApplicationContext()).setLatitude("34.75");
            ((BaseApplication) this.getApplicationContext()).setLongitude("113.60");
            ((BaseApplication) this.getApplicationContext()).setAddress("河南省郑州市中原区");
            ((BaseApplication) this.getApplicationContext()).setDefaultCityCode("179");

            // 检查版本号
            checkVersion();
            registBroadcast();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 检查版本更新
     */
    private void checkVersion() {
        UpdataAPK updataAPK = new UpdataAPK(this, getResources().getString(
                R.string.update_appname), getResources().getString(
                R.string.kckpServerUrl), URLConstant.CHECKVERSION,
                getResources().getString(R.string.updatekey));
        updataAPK.checkVersion();
    }

    /**
     * 注册广播监听是否被挤掉或超时
     */
    private void registBroadcast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.longrise.loginForCookId");
        filter.addAction("com.longrise.loginout");
        this.registerReceiver(receiver, filter);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String packName = intent.getStringExtra("packageName");
            if (TextUtils.equals(packName, MainActivity.this.getPackageName())) {
                String aciton = intent.getAction();
                if (TextUtils.equals(aciton, "com.longrise.loginout")) {//账号被挤掉
                    showDialog("您的账号已在其他设备登录，如非本人操作，请及时更改密码！");
                }
//                else if (TextUtils.equals(aciton, "com.longrise.loginForCookId")) {//登录超时
//                    String data = intent.getStringExtra("data");
//                    if (TextUtils.isEmpty(data)) {//重新登录失败
//                        showDialog("登录失效，请退出重新登录");
//                    }
//                }
            }
        }
    };

    private void showDialog(String msg) {
        if (null == dialog) {
            dialog = new PromptDialog(this);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setCancel("退出", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    //回到登录页
//                    if (FrameworkManager.getInstance().isPopForm()) {
//                        FrameworkManager.getInstance().closePopForm();
//                    }
                    FrameworkManager.getInstance().destroyAllForm();
                }
            });
            dialog.setConfirm("重新登录", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    againLogin();
                }
            });
        }
        dialog.setInfo(msg);
        dialog.show();
    }

    //被挤掉后重新登录
    private void againLogin() {
        try {
            DialogUtils.showDialog(this);
            String userflag = ((BaseApplication) getApplication()).getKckpName();
            String pwd = ((BaseApplication) getApplication()).getKckpPass();
            ApiImpI.getInstance(getApplicationContext()).login(userflag, pwd, new ApiImpI.RequestCallBack() {
                @Override
                public void onError(String error) {
                    DialogUtils.closeDialog();
                    if (!TextUtils.isEmpty(error)) {
                        UiUtil.showToast(MainActivity.this, error);
                    }
                }

                @Override
                public void onSuccess(Object result) {
                    DialogUtils.closeDialog();
                    EntityBean bean = (EntityBean) result;
                    String restate = bean.getString("restate");
                    if (TextUtils.equals(restate, "1")) {
                        EntityBean dataBean = bean.getBean("data");
                        if (null != dataBean) {
                            String token = dataBean.getString("token", "");
                            BaseApplication application = (BaseApplication) getApplication();
                            //缓存数据
                            application.setToken(token);
                            application.setLoginInfo(dataBean);
                            // 将菜单存到本地
                            String userInfoStr = com.longrise.LEAP.Base.IO.JSONSerializer.getInstance().Serialize(dataBean);
                            PrefUtils.setString(MainActivity.this, "loginInfo", userInfoStr);

                            UiUtil.showToast(MainActivity.this, "重新登录成功");
                        }
                    } else {
                        String redes = bean.getString("redes");
                        UiUtil.showToast(MainActivity.this, redes);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    public void onResume() {
        StatService.onResume(this);
        super.onResume();
    }

    @Override
    public void onPause() {
        StatService.onPause(this);
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public Object onLSMsg(int type, Object... parameters) {
        // 退出
        if (-1 == type) {
            if (null != parameters && 1 == parameters.length && parameters[0].toString().equals("exit")) {
                isExit = true;
                MainActivity.this.finish();
            }
        }
        // 设置横竖屏
        else if (1 == type) {
            if (null != parameters && 2 == parameters.length && parameters[0].toString().equals("screenState")) {
                // 自动
                if ("0".equals(parameters[1].toString())) {
                    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                }
                // 横屏
                else if ("1".equals(parameters[1].toString())) {
                    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
                // 竖屏
                else if ("2".equals(parameters[1].toString())) {
                    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
            }
        }
        // 设置主题
        else if (2 == type) {
            if (null != parameters && 2 == parameters.length && parameters[0].toString().equals("themeId")) {
                if ("1".equals(parameters[1].toString())) {
                    this.getSharedPreferences(Global.getInstance().getSPName(), Context.MODE_PRIVATE).edit()
                            .putInt("themeId", 1).commit();
                } else if ("2".equals(parameters[1].toString())) {
                    this.getSharedPreferences(Global.getInstance().getSPName(), Context.MODE_PRIVATE).edit()
                            .putInt("themeId", 2).commit();
                }
                this.isExit = false;
                this.isRestart = true;
                MainActivity.this.finish();
            }
        }
        // 设置字体
        else if (3 == type) {
            if (null != parameters && 2 == parameters.length && parameters[0].toString().equals("fontId")) {
                // 当前字体判断
                if ("0".equals(parameters[1].toString())) {
                    Global.getInstance().setFontType(0);

                } else if ("1".equals(parameters[1].toString())) {
                    Global.getInstance().setFontType(1);
                } else if ("2".equals(parameters[1].toString())) {
                    Global.getInstance().setFontType(2);
                }

                this.isExit = false;
                this.isRestart = true;
                MainActivity.this.finish();
            }
        }
        return null;
    }

    @Override
    public void OnTask() {
        // 启动定时服务调用，避免app超时{
        Thread thread = new Thread(null, _mainTask, "getIpThreadBackground");
        thread.start();
    }

    @Override
    protected void onDestroy() {
        // 清除缓存
        if (null != sharedPreferences) {
            if (sharedPreferences.getBoolean("ISCLEAR", true)) {
                this.clearCache();
            }
        }
        sharedPreferences = null;
        // 清除缓存

        if (null != this._bodyView) {
            this._bodyView.removeAllViewsInLayout();
        }
        this._bodyView = null;

        // 横竖屏切换时不清除Global里的数据，退出时清除
        if (this.isExit) {
            new Thread(_dologout);
        }

        // 主题切换
        if (isRestart) {
            isRestart = false;
            this.startActivity(new Intent(MainActivity.this, MainActivity.this.getClass()));
        }
        this.removeILSMsgListener(this);// 移除全局事件监听

        if (Global.getInstance() != null) {
            Global.getInstance().onDistory();
        }
        DialogUtils.destroyDialog();
        this.unregisterReceiver(receiver);
        super.onDestroy();// 此句必须放最后

        System.exit(0);
    }

    // 避免session超时{ run at background
    private Runnable _mainTask = new Runnable() {
        @Override
        public void run() {
            UserInfo uinfo = null;
            try {
                // Global.getInstance().call("app_getIP", String.class);
                uinfo = (UserInfo) Global.getInstance().call("app_getUserInfo", UserInfo.class);
                if (null == uinfo) {
                    // reLogin();
                } else {
                    Global.getInstance().setUserInfo(uinfo);
                }
            } catch (Exception ex) {
            } finally {
                uinfo = null;
            }

        }
    };

    /**
     * 登出(background thread)
     */
    private Runnable _dologout = new Runnable() {

        @Override
        public void run() {
            Global.getInstance().call("logout", null);
            Global.getInstance().onDistory();
        }
    };

    /**
     * handle回调方法
     */
    @Override
    public boolean handleMessage(Message message) {
        return false;
    }

    public void setOnActivityReturnBitmap(OnActivityReturnBitmap oarb) {
        this.activityReturnBitmap = oarb;
    }

    @Override
    public void onExecption(String exception) {

    }

    public interface OnActivityReturnBitmap {
        public void activityReturnBitmap(int requestCode, int resultCode, Intent data);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (null != activityReturnBitmap) {
            this.activityReturnBitmap.activityReturnBitmap(requestCode, resultCode, data);
        }
    }
}
